import React, { useState } from "react";
import {
  DashboardOutlined,
  AppstoreOutlined,
  ShoppingOutlined,
  DatabaseOutlined,
  SettingOutlined,
  TeamOutlined,
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { Button, Layout, Menu, theme, Image, Avatar } from "antd"; // 移除多余的Tooltip组件
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import confirm from "antd/es/modal/confirm";

const { Header, Sider, Content } = Layout;

const App: React.FC = () => {
  const router = useNavigate();
  const [collapsed, setCollapsed] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const location = useLocation();
  const { token } = theme.useToken();

  // 左侧菜单数据
  const menuItems = [
    { key: "/Layout/Home", icon: <DashboardOutlined />, label: "仪表盘" },
    {
      key: "/Layout/Cangku",
      icon: <AppstoreOutlined />,
      label: "仓库管理",
      children: [
        { key: "/Layout/Cangku/Cangku", label: "仓库管理" },
        { key: "/Layout/Cangku/Kuqu", label: "库区管理" },
        { key: "/Layout/Cangku/Kuwei", label: "库位管理" },
      ],
    },
    {
      key: "/Layout/ChuRu",
      icon: <TeamOutlined />,
      label: "出入库管理",
      children: [
        { key: "/Layout/ChuRu/Rukugl", label: "入库管理" },
        { key: "/Layout/ChuRu/Ckgl", label: "出库管理" },
        { key: "/Layout/ChuRu/Rkjilu", label: "入库记录" },
        { key: "/Layout/ChuRu/Ckjilu", label: "出库记录" },
        { key: "/Layout/ChuRu/Kcyiwei", label: "库存移位" },
      ],
    },
    {
      key: "/Layout/Kucun",
      icon: <ShoppingOutlined />,
      label: "库存查询",
      children: [{ key: "/Layout/Kucun/Query", label: "库存查询" }],
    },
    {
      key: "/Layout/Jichu",
      icon: <DatabaseOutlined />,
      label: "基础资料",
      children: [
        { key: "/Layout/Jichu/Product", label: "产品管理" },
        { key: "/Layout/Jichu/Customer", label: "客户管理" },
        { key: "/Layout/Jichu/Field", label: "字段管理" },
      ],
    },
    {
      key: "/Layout/System",
      icon: <SettingOutlined />,
      label: "系统设置",
      children: [
        { key: "/Layout/System/User", label: "用户管理" },
        { key: "/Layout/System/Department", label: "部门管理" },
        { key: "/Layout/System/Permission", label: "权限管理" },
      ],
    },
  ];

  // 图片路径（替换为你的实际图片路径）
  const avatarImgUrl = "/image/手榴弹.png";
  const username = localStorage.getItem("username") || "管理员";

  return (
    <Layout style={{ height: "100vh" }}>
      {/* 左侧侧边栏 */}
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
        width={200}
        style={{
          backgroundColor: "#fff",
          borderRight: `1px solid ${token.colorBorder}`,
        }}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            padding: "0 16px",
            height: 64,
            borderBottom: `1px solid ${token.colorBorder}`,
          }}
        >
          <img
            src="/image/cangchu.png"
            alt="logo"
            style={{ width: 32, height: 32, marginRight: 8 }}
          />
          {!collapsed && (
            <span style={{ fontSize: 16, fontWeight: "bold" }}>通用wms</span>
          )}
        </div>
        <Menu
          mode="inline"
          selectedKeys={[location.pathname]}
          onClick={(e) => router(e.key)}
          items={menuItems}
          style={{ borderRight: "none", backgroundColor: "#fff" }}
        />
      </Sider>

      <Layout style={{ height: "100vh", overflow: "hidden" }}>
        {/* 顶部Header */}
        <Header
          style={{
            padding: "0 24px",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            background: "#fff",
            borderBottom: `1px solid ${token.colorBorder}`,
            boxShadow: "0 1px 2px rgba(0,0,0,0.03)",
            height: 64,
          }}
        >
          {/* 菜单折叠/展开按钮 */}
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{ fontSize: "16px", width: 64, height: "100%" }}
          />

          {/* 右侧用户区域（修复核心问题） */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 16,
              padding: "0 8px",
            }}
          >
            {/* 用户名称 */}
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 6,
                color: token.colorTextSecondary,
                fontSize: 14,
              }}
            >
              <UserOutlined
                style={{ fontSize: 16, color: token.colorPrimary }}
              />
              <span>{username}</span>
            </div>

            {/* 用户头像（完全修复：取消Tooltip+修正fallback+简化交互） */}
            <Avatar
              // 修复1：Avatar的src直接传图片路径（无需嵌套Image，避免层级冲突）
              src={avatarImgUrl}
              alt="用户头像"
              // 修复2：fallback使用正确类型（ReactNode，支持图标），解决报红
              icon={<UserOutlined style={{ fontSize: 18 }} />}
              style={{
                width: 36,
                height: 36,
                cursor: "pointer",
                border: `2px solid ${token.colorBgContainer}`,
                boxShadow: "0 1px 3px rgba(0,0,0,0.1)",
                transition: "transform 0.2s ease",
              }}
              // 修复3：仅保留点击预览，取消鼠标划过的多余提示
              onClick={() => setPreviewVisible(true)}
            />

            {/* 图片预览组件（独立渲染，避免与Avatar嵌套冲突） */}
            <Image
              preview={{
                visible: previewVisible,
                onVisibleChange: (visible) => setPreviewVisible(visible),
                mask: "rgba(0,0,0,0.8)",
                toolbarRender: () => null,

              }}
              // 隐藏默认图片（仅用预览功能）
              style={{ display: "none" }}
              src={avatarImgUrl}
              alt="用户头像预览"
            />

            {/* 退出登录按钮（修复hover样式报红） */}
            <Button
              type="text"
              danger
              onClick={() => {
                confirm({
                  title: "确定退出登录吗？",
                  okText: "退出",
                  cancelText: "取消",
                  onOk: () => {
                    localStorage.removeItem("username");
                    router("/Login");
                  },
                  okButtonProps: { danger: true },
                  cancelButtonProps: { style: { marginRight: 8 } },
                });
              }}
              // 修复4：移除inline的&:hover（React内联样式不支持选择器），改用AntD自带danger属性样式
              style={{
                fontSize: 14,
                padding: "4px 12px",
                borderRadius: 4,
              }}
            >
              退出登录
            </Button>
          </div>
        </Header>

        {/* 中间内容区域 */}
        <Content
          style={{
            margin: "24px",
            padding: 24,
            background: "#fff",
            borderRadius: 8,
            boxShadow: "0 1px 4px rgba(0,0,0,0.05)",
            height: "calc(100vh - 136px)",
            overflow: "scroll",
          }}
        >
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default App;
